package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.store.dao.YunscStoreSettingDao;
import com.yunsc.store.dto.StoreSettingDTO;
import com.yunsc.store.entity.YunscExpressEntity;
import com.yunsc.store.entity.YunscStoreSettingEntity;
import com.yunsc.store.service.YunscExpressService;
import com.yunsc.store.service.YunscStoreSettingService;
import com.yunsc.store.vo.FullFreeSettingVO;
import com.yunsc.store.vo.OrderSettingVO;
import com.yunsc.store.vo.SMSNoticeVO;
import com.yunsc.store.vo.SettingDeliveryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("yunscStoreSettingService")
public class YunscStoreSettingServiceImpl extends ServiceImpl<YunscStoreSettingDao, YunscStoreSettingEntity> implements YunscStoreSettingService {

    @Resource
    private YunscExpressService expressService;

    // 根据key查询店铺设置
    @Override
    public YunscStoreSettingEntity queryStoreSettingByKey(String key, Integer storeId) {
        YunscStoreSettingEntity storeSettingEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>()
                .eq("`key`", key)
                .eq("store_id", storeId));

        return storeSettingEntity;
    }


    @Override
    @Transactional
    public void updateStoreSetting(StoreSettingDTO params) {
        String key = params.getKey();
        QueryWrapper<YunscStoreSettingEntity> queryWrapper = new QueryWrapper<YunscStoreSettingEntity>()
                .eq("`key`", key);
        YunscStoreSettingEntity storeSettingEntity = this.getOne(queryWrapper);
        if (storeSettingEntity == null) {
            throw new YunscException("店铺设置不存在");
        }
        Object form = params.getForm();
        if ("sms".equals(key)){
            Map map = JSON.parseObject(JSON.toJSONString(form), Map.class);
            SMSNoticeVO smsNoticeVO = JSON.parseObject(JSON.toJSONString(form), SMSNoticeVO.class);
            smsNoticeVO.setDefaultEngine(map.get("default").toString());
            storeSettingEntity.setValues(JSON.toJSONString(smsNoticeVO));
        }else {
            storeSettingEntity.setValues(JSON.toJSONString(form));
        }


        this.update(storeSettingEntity, queryWrapper);
    }

    @Override
    public List<YunscExpressEntity> queryExpressAll(Integer storeId) {
        return expressService.list(new QueryWrapper<YunscExpressEntity>().eq("store_id", storeId));
    }

    /*@Override
    public Map<String, Object> queryStoreSettingAll(Integer storeId) {
        // 查询店铺设置
        Map<String, Object> settingMap = new HashMap<>();
        YunscStoreSettingEntity appThemeEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "app_theme"));
        Object appThemeForm = JSON.parseObject(appThemeEntity.getValues());
        if (appThemeForm != null) {
            settingMap.put("app_theme", JSON.parseObject(appThemeForm.toString(), Map.class).get("data"));
        }
        YunscStoreSettingEntity customerEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "customer"));
        if (customerEntity != null) {
            settingMap.put("customer", JSON.parseObject(customerEntity.getValues()));
        }
        YunscStoreSettingEntity pageCategoryTemplateEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "page_category_template"));
        if (pageCategoryTemplateEntity != null) {
            settingMap.put("page_category_template", JSON.parseObject(pageCategoryTemplateEntity.getValues()));
        }
        YunscStoreSettingEntity pointsEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "points"));
        if (pointsEntity != null) {
            settingMap.put("points", JSON.parseObject(pointsEntity.getValues()));
        }
        YunscStoreSettingEntity rechargeEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "recharge"));
        if (rechargeEntity != null) {
            settingMap.put("recharge", JSON.parseObject(rechargeEntity.getValues()));
        }
        YunscStoreSettingEntity registerEntity = this.getOne(new QueryWrapper<YunscStoreSettingEntity>().eq("`key`", "register"));
        if (registerEntity != null) {
            settingMap.put("register", JSON.parseObject(registerEntity.getValues()));
        }
        return settingMap;
    }*/
    @Override
    public Map<String, Object> queryStoreSettingAll(Integer storeId) {
        // 查询店铺设置
        Map<String, Object> settingMap = new HashMap<>();
        LambdaQueryWrapper<YunscStoreSettingEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscStoreSettingEntity::getStoreId, storeId);
        List<YunscStoreSettingEntity> settings = this.list(lqw);
        for (YunscStoreSettingEntity setting : settings) {
            String key = setting.getKey();
            if (key != null) {
                switch (key) {
                    case "app_theme":
                        settingMap.put("app_theme", JSON.parseObject(setting.getValues(), Map.class).get("data"));
                        break;
                    case "customer":
                    case "page_category_template":
                    case "points":
                    case "recharge":
                    case "register":
                        settingMap.put(key, JSON.parseObject(setting.getValues()));
                        break;
                    default:
                        // 如果有其他设置，可以在此处进行处理
                        break;
                }
            }
        }
        return settingMap;
    }



    @Override
    public String queryPointData(Integer storeId) {
        YunscStoreSettingEntity storeSettingEntity = this.getOne(new LambdaQueryWrapper<YunscStoreSettingEntity>()
                .eq(YunscStoreSettingEntity::getStoreId, storeId)
                .eq(YunscStoreSettingEntity::getKey, "points"));
        return storeSettingEntity == null ? "" : storeSettingEntity.getValues();

    }

    @Override
    public List<Integer> queryStoreDelivery(Integer storeId) {
        YunscStoreSettingEntity storeSettingEntity = this.getOne(new LambdaQueryWrapper<YunscStoreSettingEntity>()
                .eq(YunscStoreSettingEntity::getStoreId, storeId)
                .eq(YunscStoreSettingEntity::getKey, "delivery"));
        SettingDeliveryVO deliveryVO = JSON.parseObject(storeSettingEntity.getValues(), SettingDeliveryVO.class);
        return deliveryVO.getDeliveryType();
    }

    @Override
    public boolean queryIsFreePostage(Integer storeId, Integer cityId, BigDecimal orderTotalPrice) {
        YunscStoreSettingEntity storeSettingEntity = this.getOne(new LambdaQueryWrapper<YunscStoreSettingEntity>()
                .eq(YunscStoreSettingEntity::getStoreId, storeId)
                .eq(YunscStoreSettingEntity::getKey, "full_free"));
        if (storeSettingEntity == null || cityId == null || orderTotalPrice == null) {
            return false;
        }
        FullFreeSettingVO fullFreeSetting = JSON.parseObject(storeSettingEntity.getValues(), FullFreeSettingVO.class);
        // 开启全免邮 1 关闭全免邮 0
        if (fullFreeSetting.getIsOpen() == 1) {
            int money = fullFreeSetting.getMoney(); // 免邮金额
            // 全免邮城市列表 包含当前城市 并且 订单金额大于等于免邮金额
            return fullFreeSetting.getExcludedRegions().getCityIds().contains(cityId) && orderTotalPrice.compareTo(new BigDecimal(money)) >= 0;
        }
        return false;
    }

    @Override
    public OrderSettingVO queryOrderSettingVO(Integer storeId) {
        LambdaQueryWrapper<YunscStoreSettingEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscStoreSettingEntity::getStoreId, storeId)
               .eq(YunscStoreSettingEntity::getKey, "trade");
        YunscStoreSettingEntity storeSettingEntity = this.getOne(lqw);
        if (storeSettingEntity == null) {
            throw new YunscException("订单设置不存在");
        }
        return JSON.parseObject(storeSettingEntity.getValues(), OrderSettingVO.class);
    }

    @Override
    public SMSNoticeVO querySMSSettingVO(Integer storeId) {
        LambdaQueryWrapper<YunscStoreSettingEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscStoreSettingEntity::getStoreId, storeId)
                .eq(YunscStoreSettingEntity::getKey, "sms");
        YunscStoreSettingEntity storeSettingEntity = this.getOne(lqw);
        if (storeSettingEntity == null) {
            throw new YunscException("订单设置不存在");
        }
        SMSNoticeVO smsNoticeVO = JSON.parseObject(storeSettingEntity.getValues(), SMSNoticeVO.class);
        String values = storeSettingEntity.getValues();
        Map<String, List<String>> captchaMap = new HashMap<>();
        captchaMap.put("aliyun", Collections.singletonList("${code}"));
        captchaMap.put("qcloud", Collections.singletonList("{1}"));
        captchaMap.put("qiniu", Collections.singletonList("${code}"));
        smsNoticeVO.getScene().getCaptcha().setVariables(captchaMap);
        Map<String, List<String>> orderMap = new HashMap<>();
        orderMap.put("aliyun", Collections.singletonList("${order_no}"));
        orderMap.put("qcloud", Collections.singletonList("{1}"));
        orderMap.put("qiniu", Collections.singletonList("${order_no}"));
        smsNoticeVO.getScene().getOrderPay().setVariables(orderMap);
        return smsNoticeVO;
    }
}